let {createOrder,findOrder,update} =require('../server/order.js')
async function create(ctx){
    let user_id=ctx.state.user.id
    let data={
        user_id,
        ...ctx.request.body,
        order_number:'XZD'+Date.now()
    }
    try{
        let res=await createOrder(data)
        console.log(res,'ddddddd')
        if(res){
            ctx.body={
                code:200,
                message:"订单创建成功",
                result:res
            }
        }else{
            ctx.app.emit('error',{
                code:50000,
                message:"订单创建失败",
                result:""
            },ctx)
        }
    }catch(error){
        ctx.app.emit('error',{
            code:50000,
            message:"订单创建失败"+error,
            result:""
        },ctx)
    }
   
}

async function getOrder(ctx){
   let user_id=ctx.state.user.id
   try{
    let res=await findOrder(user_id)
    
    ctx.body={
        code:200,
        message:"获取订单成功",
        result:res
    }
   }catch(error){
     ctx.app.emit('error',{
         code:50000,
         message:'获取订单失败'+error,
         result:''
     },ctx)
   }
   

}

async function updateOrder(ctx){
    console.log('contral',ctx.request.params.id,ctx.request.body)
    let order_number=ctx.request.params.id
    let {status}=ctx.request.body
    console.log({order_number,status},'....')
    try{
        let res=await update({order_number,status}) 
        if(res[0]>0){
            ctx.body={
                code:200,
                message:"订单状态改变成功",
                result:res
            }
        }else{
            ctx.app.emit('error',{
                code:50000,
                message:'订单状态改变失败',
                result:''
            },ctx)
        }
        
    }catch(error){
        ctx.app.emit('error',{
            code:50000,
            message:'订单状态改变失败'+error,
            result:''
        },ctx)
    }
    

}

module.exports={
    create,
    getOrder,
    updateOrder
}